<template>
    <div class="notic-add">
        <div class="bg">
            <div class="logo" @click="toNoticList">
                <img src="../../assets/logo.png" alt="" @click.stop="toHome">
                <div>
                    通知公告
                </div>
            </div>
        </div>
        <div class="content">
            <h3>新建公告</h3>
            <div class="form">
                <div class="left">
                    <el-form :rules="rules" ref="form" :model="form" label-width="120px">
                        <el-form-item label="发布人 :">
                            {{ userInfo.realName }}
                        </el-form-item>
                        <el-form-item label="发布人所在部门 :">
                            {{ form.department }}
                        </el-form-item>
                        <el-form-item label="公告类型 :" prop="types">
                            <el-select v-model="form.types" clearable placeholder="请选择公告类型">
                                <el-option v-for="item in noticClassifys" :key="item.value" :label="item.label"
                                    :value="item.label">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="公告标题 :" prop="title">
                            <el-input v-model="form.title" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="公告内容 :" prop="content">
                            <RichEditor @onChange="onEditChange" :resetHtml="resetHtml" />
                        </el-form-item>
                        <el-form-item label="上传附件 :">
                            <el-upload class="upload-demo" ref="upload" action="#" :http-request="null"
                                :on-change="attChange" :before-remove="handleAttachRemove" :auto-upload="false">
                                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                                <div slot="tip" class="el-upload__tip">只能上传不超过4MB大小的文件</div>
                            </el-upload>
                        </el-form-item>
                        <el-form-item class="btns">
                            <el-button @click="resetForm('form')">重置</el-button>
                            <el-button :disabled="submitting" type="primary" @click="submitForm('form')">发布</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="right">
                    <h3>通知公告接收人:</h3>
                    <el-input placeholder="请输入..." v-model="filterText">
                    </el-input>
                    <el-tree class="filter-tree" @check-change="onSelectReceiver" :data="deptList" show-checkbox
                        node-key="id" ref="tree" highlight-current :props="defaultProps">
                    </el-tree>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import RichEditor from '../../components/RichEditor.vue';
import { noticeAdd, listNoticeTypes } from "@/api/notice";
import { getUserByCRP } from '@/api/user';
import { listDept } from "@/api/department";
import { otherUpload } from "@/api/upload";
import { mapGetters } from 'vuex';
export default {
    name: 'NoticAdd',
    components: {
        RichEditor,
    },
    data() {
        return {
            submitting: false,
            noticClassify: [],//公告类型
            noticClassifys: [],//公告类型列表
            form: {
                senderId: localStorage.getItem("userId"),//发布人id
                department: '电子信息工程学院',//发布部门
                types: '',
                title: '',
                content: '',
                //附件列表
                attachList: [],
                receiverTypeList: ""
            },
            attachArr: [],
            // localFileList: [],//本地附件列表
            //表单非空校验
            rules: {
                types: [
                    { required: true, message: '请选择公告类型', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入公告标题', trigger: 'blur' },
                ],
                content: [
                    { required: true, message: '请输入公告内容', trigger: 'blur' },
                ],
            },
            filterText: '',
            deptList: [],
            selectedIds: [],
            defaultProps: {
                children: 'children',
                label: 'nodeName',
                id: "id"
            },
            resetHtml: "",
            userInfo: {}
        }
    },
    computed: {
        ...mapGetters({
            user: 'user', // 将 'user' getter 映射为 'userName' computed 属性
        }),
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    mounted() {
        this.getNoticType();
        this.getListDept();
        this.getDeptName();
    },
    methods: {
        // 额外的方法，用于在需要时获取所有节点的 ID（不论是否选中）
        getAllNodeIds() {
            const allIds = [];
            const collectAllIds = (node) => {
                allIds.push(node.id);
                if (node.children) {
                    node.children.forEach(child => collectAllIds(child));
                }
            };
            this.$refs.tree.store.root.children.forEach(node => {
                collectAllIds(node);
            });
            return allIds;
        },
        //根据部门id 查询部门名称
        getDeptName() {
            const userName = localStorage.getItem("CRP")
            if (userName != undefined) {
                getUserByCRP(userName).then(res => {
                    if(res.code == 200){
                        this.userInfo = res.data
                    }
                })
            }
            // console.log(this.user.departmentId)
        },
        toNoticList() {
            this.$router.push("/notification")
        },
        toHome() {
            this.$router.push("/teacher")
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.nodeName.indexOf(value) !== -1;
        },
        //查询部门
        getListDept() {
            listDept().then(res => {
                this.deptList = res.data[0].children;
            })
        },
        // 处理复选框选中变化的事件
        onSelectReceiver() {
            const checkedNodes = this.$refs.tree.getCheckedNodes(true); // true 表示包括半选节点
            const selectedIds = checkedNodes.map(node => node.id);
            this.form.receiverTypeList = JSON.stringify(selectedIds);
        },
        //查询公告类型
        getNoticType() {
            listNoticeTypes().then(res => {
                this.noticClassifys = res.data.map(dept => {
                    return {
                        value: dept.ntypeId,
                        label: dept.ntypeName,
                    }
                })
            })
        },
        onEditChange(data) {
            this.form.content = data;
        },
        submitForm(formName) {
            this.form.attachList = JSON.stringify(this.attachArr);
            // this.form.attachList = `[${this.attachArr.map(id => id.toString()).join(',')}]`;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitting = true;
                    noticeAdd(this.form).then(res => {
                        if (res.code == 200) {
                            this.$message({
                                message: '公告发布成功',
                                type: 'success'
                            });
                            setTimeout(() => {
                                this.$router.push("/myNotic")
                            })
                            this.submitting = false;
                        }
                    })
                } else {
                    return false;
                }
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.resetHtml = "";
        },
        //附件上传
        attChange(file) {
            const fileSize = file.size;
            const maxFileSize = 4 * 1024 * 1024; // 4MB = 4 * 1024 KB = 10 * 1024 * 1024 B
            // 检查文件大小是否超过限制
            if (fileSize > maxFileSize) {
                this.$message.error('文件大小不能超过4MB');
                this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file), 1);
                return true;
            }
            const allowedFileTypes = [
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',       // .xlsx
                'application/vnd.openxmlformats-officedocument.presentationml.presentation',// .pptx
                'application/pdf',                                                         // .pdf
                'application/x-zip-compressed',                                                          // .zip
                'text/plain',                                                             // .txt
                'application/xml',                                                         // 通常用于 .xsl 文件，但也可能遇到 text/xsl
                'text/xsl',                                                                // 另一种可能的 .xsl 文件 MIME 类型
                'application/x-compressed'                                             // .rar 文件
            ];
            // 检查文件类型是否允许
            if (!allowedFileTypes.includes(file.raw.type)) {
                this.$message.error('上传的文件格式不允许');
                this.$refs.upload.uploadFiles.splice(this.$refs.upload.uploadFiles.indexOf(file), 1);
                return true;
            }
            const formData = new FormData();
            formData.append('files', file.raw);
            otherUpload(formData).then(response => {
                // 处理成功响应
                this.$message({
                    message: '附件上传成功',
                    type: 'success'
                });
                console.log(response.data[0])
                this.attachArr.push(response.data[0]);
            }).catch(error => {
                // 处理错误响应
                console.error('上传失败:', error);
            });
        },
        //附件移除
        handleAttachRemove(file, fileList) {
            const index = fileList.findIndex(item => item.name === file.name && item.size === file.size);
            this.attachArr.splice(index, 1);
        }
    }
}
</script>

<style lang="scss" scoped>
.notic-add {
    background-color: #F1F3F5;
    height: 100vh;
    padding-top: 120px;

    .bg {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 110px;
        z-index: 999;
        background: url("../../assets/notic-bg.jpg") no-repeat;
        background-color: #F1F3F5;

        .logo {
            padding: 10px 40px;
            display: flex;
            align-items: center;

            &>div {
                color: white;
                margin-left: 10px;
                border-left: 1px solid white;
                padding: 14px 0;
                padding-left: 15px;
            }
        }
    }

    .content {
        margin: 10px 80px 0;
        // box-shadow: 1px 0px 10px gray;
        padding: 20px;
        background-color: white;

        h3 {
            text-align: center;
            margin-bottom: 20px;
        }

        .form {
            display: flex;

            .left {
                flex: 1.5;
                border-right: 1px solid #ccc;
                padding-right: 20px;

                .el-form {
                    :deep .el-form-item__label {
                        font-weight: bold;
                        color: #000;
                    }

                    .btns {
                        display: flex;
                        justify-content: end;

                        .el-button {
                            width: 150px;
                        }
                    }
                }
            }

            .right {
                flex: 0.5;
                height: 500px;
                margin-left: 10px;

                h3 {
                    text-align: left;
                }

                .filter-tree {
                    margin-top: 15px;

                    :deep .el-tree-node__content {
                        margin-bottom: 4px;
                    }
                }
            }
        }
    }

}
</style>